package com.yyz.lease.web.admin.service.impl;

import com.yyz.lease.common.minio.MinioProperties;
import com.yyz.lease.web.admin.service.FileService;
import io.minio.*;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
@RequiredArgsConstructor
public class FileServiceImpl implements FileService {
    private final MinioClient client;
    private final MinioProperties properties;

    @Override
    public String upload(MultipartFile file) throws Exception{
        //创建桶
        //1.判断桶是否存在
        boolean bucketExists = client.bucketExists(
                BucketExistsArgs.builder()
                        .bucket(properties.getBucketName())
                        .build()
        );
        if (!bucketExists) {
            //不存在，创建
            client.makeBucket(
                    MakeBucketArgs
                            .builder()
                            .bucket(properties.getBucketName())
                            .build()
            );
            //设置访问权限
            client.setBucketPolicy(
                    SetBucketPolicyArgs
                            .builder()
                            .bucket(properties.getBucketName())
                            .config(createBucketPolicyConfig(properties.getBucketName()))
                            .build()
            );
        }
        // 文件夹名称（当前日期）-> 文件名：uuid - 文件名
        String filename = new SimpleDateFormat("yyyyMMdd").format(new Date()) +
                "/" + UUID.randomUUID() + "-" + file.getOriginalFilename();

        //上传图片
        client.putObject(
                PutObjectArgs.builder().
                        bucket(properties.getBucketName()).
                        object(filename).
                        stream(file.getInputStream(), file.getSize(), -1).
                        contentType(file.getContentType())//指定上传文件的数据类型
                        .build()
        );

        return String.join(
                "/",
                properties.getEndpoint(), properties.getBucketName(), filename
        );

    }

    /**
     * 生成用于描述指定bucket访问权限的JSON字符串
     *
     * @param bucketName 桶名
     * @return 指定bucket访问权限的JSON字符串
     */
    private String createBucketPolicyConfig(String bucketName) {
        return """
                {
                  "Statement" : [ {
                    "Action" : "s3:GetObject",
                    "Effect" : "Allow",
                    "Principal" : "*",
                    "Resource" : "arn:aws:s3:::%s/*"
                  } ],
                  "Version" : "2012-10-17"
                }
                """.formatted(bucketName);
    }
}
